<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      :on-preview="preview"
      :file-list=" fileList"
      action="#"
      :class="{ disabled : fileComputed}"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
      <el-progress v-if="percentShow" :percentage="percent" />
    </el-upload>
    <el-dialog title="图片" :visible.sync="showDialog">
      <img :src="imgUrl" style="width:100%" alt="">
    </el-dialog>
  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDnPlrhGZbNuA9sKVQ4SZPyGJ5aolSs1tU',
  SecretKey: 'NTHo68tNccK2UfhTyIM9fusYx5wWprc5'
})
export default {
  data() {
    return {
      showDialog: false,
      imgUrl: '',
      fileList: [],
      fileUid: '',
      percent: 0,
      percentShow: false
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      console.log(file)
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    changeFile(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      // 判断图片格式中有没有types中的格式
      console.log(file.type, file.size, 111)
      if (!types.some(item => item === file.type)) {
        this.$message.error('上传的图片只能是 JPG GIF BMP PNG  格式')
        return false
      } else {
        // 限制文件大小
        const maxSize = 5 * 1024 * 1024
        if (file.size > maxSize) {
          this.$message.error('上传的图片不能大于5M')
          return false
        }
        this.fileUid = file.uid
        this.percentShow = true
        return true
      }
    },
    upload(params) {
      if (params.file) {
        // 腾讯云上传图片操作
        cos.putObject({
          Bucket: 'ydwc-1307714034',
          Region: 'ap-guangzhou',
          Key: params.file.name,
          Body: params.file,
          StorageClass: 'STANDARD',
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          console.log(err, data, 999)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.fileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            this.percentShow = false
          }
        })
      }
    }
  }
}
</script>

<style >
.disabled .el-upload{
display: none ;
}
</style>

